package com.bigger.task;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.bigger.entity.Order;
import com.bigger.entity.User;
import com.bigger.mapper.OrderDetailMapper;
import com.bigger.mapper.OrderMapper;
import com.bigger.mapper.UserMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.List;

@Component
@Slf4j
public class AdminTask {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private OrderDetailMapper orderDetailMapper;
    /**
     * 处理超时vip方法
     */
    @Scheduled(cron = "0 0 * * * ? ") //每小时执行一次
    public void handleTimeoutVIP(){
        log.info("处理超时vip方法,已开始进行。。。。。。。。。");
        QueryWrapper<User> wrapper=new QueryWrapper<User>()
                .le("expiration_time", LocalDateTime.now(ZoneId.of("Asia/Shanghai")));
        List<User> users = userMapper.selectList(wrapper);
        if(users.isEmpty()){
            return;
        }
        List<Long> ids = users.stream().map(user -> user.getId()).toList();//lamda表达式好看一点，方法引用算了
        userMapper.batchCancelVIP(ids);
    }
    @Scheduled(cron = "0 0 0 1 * ? ") //每月执行一次
    public void handleCancelOrder(){
        log.info("处理退单订单方法,已开始进行。。。。。。。。。");
        QueryWrapper<Order> wrapper=new QueryWrapper<Order>()
                .eq("status",Order.CANCEL);//查询已取消订单
        List<Order> orders = orderMapper.selectList(wrapper);
        if(orders.isEmpty()){
            return;
        }
        orders.forEach(
                order->{
                    Long id = order.getId();
                    orderDetailMapper.deleteByOrderId(id);
                    orderMapper.deleteById(order.getId());
                }
        ); //和for循环一个道理
    }
}
